import { Toast } from 'antd-mobile'
import axios from 'axios'
import history from './history'
import { getTokenInfo, setTokenInfo } from './storage'
import store from '@/store'
import { logout, saveToken } from '@/store/actions/login'
const baseURL = 'http://geek.itheima.net/v1_0'

const instance = axios.create({
  baseURL,
  timeout: 5000,
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = getTokenInfo().token
    if (token) {
      // 配置请求头
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    return response.data
  },
  async (error) => {
    if (!error.response) {
      Toast.info('网络繁忙')
      return Promise.reject(error)
    }

    // 401 token过期
    // token没过期
    if (error.response.status !== 401) {
      Toast.info(error.response.data.message)
      return Promise.reject(error)
    }
    // token过期
    const { refresh_token } = getTokenInfo()

    // 没有刷新token
    if (!refresh_token) {
      // 返回登录页
      history.push({
        pathname: '/login',
        state: { from: history.location.pathname },
      })
      return Promise.reject(error)
    }

    // 通过refresh_token获取新的token
    try {
      const { data: res } = await axios({
        method: 'PUT',
        url: baseURL + '/authorizations',
        headers: {
          Authorization: 'Bearer ' + refresh_token,
        },
      })
      const tokenInfo = {
        token: res.data.token,
        refresh_token,
      }
      // 把新的token保存到redux中
      store.dispatch(saveToken(tokenInfo))
      // 把新的token保存到本地
      setTokenInfo(tokenInfo)
      // token刷新成功后，重新把最开始的失败请求重新发一次
      return instance(error.config)
    } catch (err) {
      // 刷新token失败 刷新token过期
      // 清除本地token
      store.dispatch(logout())
      // 返回到登录页
      history.push({
        pathname: '/login',
        state: { from: history.location.pathname },
      })
      return Promise.reject(error)
    }
  }
)

export default instance
